package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class ChangeType extends BaseRFIDActivity {

    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FQty) TextView tv_FQty;
    @Bind(R.id.tv_FModel) TextView tv_FModel;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_FOldType) TextView tv_FOldType;
    @Bind(R.id.tv_FType) TextView tv_FType;
    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";
    private ArrayList<HashMap<String, Object>> mTypeList;
    private String FType = "";

    public static final int REQUESTCODE_SELECT_TYPE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_type);
        initBaseView();
        initView();
    }

    private void initView() {
        apiUrl = WebApi.production();
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));
        ll_submit.setVisibility(View.VISIBLE);

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_epc.getText().toString().equals("")) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            epc = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            getChangeTypeInfo();
        }
    }

    @OnClick(R.id.btn_select_type)
    public void selectType() {
        if (mTypeList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择状态");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mTypeList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_SELECT_TYPE);
        } else {
            Toastor.getInstance().showShortToast("无数据，请先扫卡");
        }
    }

    /**
     * 获取改状态信息
     */
    private void getChangeTypeInfo() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FActionFlag", "changeType");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getChangeTypeInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                if (data.optDouble("FCLItemID") == 0 && data.optDouble("FItemID") == 0) {
                    Toastor.getInstance().showShortToast("该卡未绑定任何产品");
                    clean();
                    return;
                }
                tv_epc.setText(data.optString("epc"));
                if (data.optDouble("FItemID") > 0) {
                    tv_FName.setText(data.optString("FName"));
                    tv_FModel.setText(data.optString("FModel"));
                    tv_FNumber.setText(data.optString("FNumber"));
                    tv_FQty.setText(String.valueOf(data.optDouble("FQty")));
                } else {
                    tv_FName.setText(data.optString("FCLName"));
                    tv_FModel.setText(data.optString("FCLModel"));
                    tv_FNumber.setText(data.optString("FCLNumber"));
                    tv_FQty.setText(String.valueOf(data.optDouble("FCLQty")));
                }
                tv_FGongxuName.setText(data.optString("FGongxuName"));
                tv_FOldType.setText(data.optString("FOldType"));

                mTypeList = new ArrayList<>();
                JSONArray list = data.optJSONArray("FTypeList");
                for (int i = 0; i < list.length(); i++) {
                    JSONObject item = list.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    map.put("FNumber", item.optString("FNumber"));
                    mTypeList.add(map);
                }
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                clean();
            }
        });
    }

    @OnClick(R.id.ll_submit)
    public void postChangeType() {
        if (tv_epc.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请先扫卡");
            return;
        } else if (tv_FType.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请选择状态");
            return;
        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("FType", FType);
        param.put("FTypeName", tv_FType.getText().toString());
        final HttpRequest client = new HttpRequest(mContext, apiUrl, "postChangeType", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(R.string.submit_success);
                clean();
            }
        });
    }

    private void clean() {
        tv_epc.setText("");
        tv_FName.setText("");
        tv_FGongxuName.setText("");
        tv_FModel.setText("");
        tv_FQty.setText("");
        tv_FNumber.setText("");
        tv_FType.setText("");
        tv_FOldType.setText("");
        FType = "";
        mTypeList = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!tv_epc.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_SELECT_TYPE && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            tv_FType.setText(mTypeList.get(p).get("FName").toString());
            FType = mTypeList.get(p).get("FNumber").toString();
        }
    }
}
